//
//  ClubMessageViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/3.
//

import UIKit

class ClubMessageViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.black).font(16.font_semiBold)
        .text("消息中心").end()
    private let readButton = c_make_ex(UIButton.self)
        .text("标记为已读").font(15.font_regular).color(.black).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubMessageTableViewCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 78.0.Scale
        return tableView
    }()
    
    private var pageIndex = 1
    private var dataSource: [ClubMessageModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            backButton
            titleLabel
            readButton
            tableView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        readButton.trailing(15)
        readButton.CenterY == backButton.CenterY
        tableView.leading(0).width(.screenWidth).top(.navi_height).bottom(0)
         
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        readButton.contentHorizontalAlignment = .right
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        readButton.addTarget(self, action: #selector(clickReadButton), for: .touchUpInside)
    }
}

extension ClubMessageViewController: UITableViewDelegate, UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubMessageTableViewCell", for: indexPath) as! ClubMessageTableViewCell
        cell.model = dataSource?[indexPath.row]
        
        let longPressG = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture(_:)))
        longPressG.minimumPressDuration = 1.0
        longPressG.numberOfTouchesRequired = 1
        cell.backView.isUserInteractionEnabled = true
        cell.backView.addGestureRecognizer(longPressG)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailVC = ClubMessageDetailViewController()
        detailVC.model = dataSource?[indexPath.row]
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}

extension ClubMessageViewController {
    
    @objc private func clickReadButton(){
        
        Task {
            let models = await network.request(.readAllList(id: ""))
            if models.isSuccess {
                
                loadNewData()
            }
        }
    }
    
    @objc private func longPressGesture(_ paramSender: UILongPressGestureRecognizer){
        
        let view = paramSender.view
        
        guard let cell = view?.superview?.superview as? ClubMessageTableViewCell else { return }
        guard let index = self.tableView.indexPath(for: cell) else { return }
        guard let model = dataSource?[index.row] as? ClubMessageModel else { return }
        
        
        let alertController = UIAlertController(title: "标记或删除", message: "标记已读或删除", preferredStyle: .actionSheet)
        let actionRead = UIAlertAction(title: "标记已读", style: .default) { alert in
            self.readMessage(msgID: model.id)
        }
        let actionDel = UIAlertAction(title: "删除", style: .default) { alert in
            self.delMessage(msgID: model.id)
        }
        let actionCancel = UIAlertAction(title: "取消", style: .cancel)
        
        alertController.addAction(actionRead)
        alertController.addAction(actionDel)
        alertController.addAction(actionCancel)
        
        present(alertController, animated: true, completion: nil)
    }
    
    private func loadData(){
        
        Task {
            let models = await network.request(.messageList(page: pageIndex),type: ClubMessageModel.self)
            tableView.refresh_end()
            if models.isSuccess, let models = models.models {
                self.dataSource = models
                self.tableView.reloadData()
            }
        }
    }
    
    private func loadNewData(){
        self.pageIndex = 1
        loadData()
    }
    
    private func loadMoreData(){
        self.pageIndex += 1
        Task {
            let models = await network.request(.messageList(page: pageIndex),type: ClubMessageModel.self)
            tableView.refresh_end()
            if models.isSuccess, let models = models.models {
                self.dataSource?.append(contentsOf: models)
                self.tableView.reloadData()
            }
        }
    }
    
    private func delMessage(msgID: String){
        Task {
            let models = await network.request(.delMessge(id: msgID))
            if models.isSuccess {
                
                loadNewData()
            }
        }
    }
    
    private func readMessage(msgID: String){
        Task {
            let models = await network.request(.readAllList(id: msgID))
            if models.isSuccess {
                
                loadNewData()
            }
        }
    }
}
